<script setup>
name: 'categories'
import { ref, onMounted } from 'vue'
import { getCategoriesListAPI, addCategoriesAPI, selectCategoriesAPI, editCategoriesAPI, delCategoriesAPI } from '@/api/productAPI'
import { ElMessage, ElMessageBox } from 'element-plus';


const queryInfo = ref({
    type: 3,
    pagenum: 1,
    pagesize: 5
})

const categorieslist = ref([])
const total = ref(0)
const getCategoriesList = async () => {
    const { data: res } = await getCategoriesListAPI(queryInfo.value)
    if (res.meta.status !== 200) return ElMessage.error(res.meta.msg)
    categorieslist.value = res.data.result
    total.value = res.data.total
}

const handleSizeChange = (val) => {
    queryInfo.value.pagesize = val
    getCategoriesList()
}

const handleCurrentChange = (val) => {
    queryInfo.value.pagenum = val
    getCategoriesList()
}

// 表单验证
const rules = {
    cat_name: [
        { required: true, message: '请输入分类名称', trigger: 'blur' },
        { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
    ],
}

// 配置
const props = ref({
    value: 'cat_id',
    label: 'cat_name',
    children: 'children',
    expandTrigger: 'hover',
    checkStrictly: true
})


// 添加分类
const addCateDialogVisible = ref(false)
const addCateForm = ref({
    cat_pid: 0,
    cat_name: '',
    cat_level: 0
})
const secondCateList = ref([])
const actionCascader = ref([])
const addCateDialog = async () => {
    const { data: res } = await getCategoriesListAPI({ type: 2 })
    if (res.meta.status !== 200) return ElMessage.error(res.meta.msg)
    secondCateList.value = res.data
    addCateDialogVisible.value = true
}
const addCateDialogClosed = () => {
    actionCascader.value = []
}

const changeActionCascader = (val) => {
    if (val.length > 0) {
        addCateForm.value.cat_pid = val[val.length - 1]
        addCateForm.value.cat_level = val.length
    } else {
        addCateForm.value.cat_pid = 0
        addCateForm.value.cat_level = 0
    }
}

const addCateRef = ref(null)
const addCate = () => {
    addCateRef.value.validate(async valid => {
        if (!valid) return
        const { data: res } = await addCategoriesAPI(addCateForm.value)
        if (res.meta.status !== 201) return ElMessage.error(res.meta.msg)
        ElMessage.success(res.meta.msg)
        addCateDialogVisible.value = false
        getCategoriesList()
    })
}

// 编辑商品
const editCateForm = ref({
    cat_id: '',
    cat_name: ''
})
const editCateDialogVisible = ref(false)
const editDialog = async (row) => {
    const { data: res } = await selectCategoriesAPI(row.cat_id)
    if (res.meta.status !== 200) return ElMessage.error(res.meta.msg)
    const { cat_id, cat_name } = res.data
    editCateForm.value = {
        cat_id,
        cat_name
    }
    editCateDialogVisible.value = true
}

const editCateRef = ref(null)
const editCateDialogClosed = () => {
    editCateRef.value.resetFields()
    editCateForm.value = {
        cat_id: '',
        cat_name: ''
    }
}
const editCate = () => {
    editCateRef.value.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await editCategoriesAPI(editCateForm.value.cat_id, editCateForm.value.cat_name)
        if (res.meta.status !== 200) return ElMessage.error(res.meta.msg)
        ElMessage.success(res.meta.msg)
        editCateDialogVisible.value = false
        getCategoriesList()
    })
}

// 删除分类
const delCate = async (row) => {
    const confirmResult = await ElMessageBox.confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).catch(err => err)
    if (confirmResult === 'confirm') {
        const { data: res } = await delCategoriesAPI(row.cat_id)
        if (res.meta.status !== 200) return ElMessage.error(res.meta.msg)
        ElMessage.success(res.meta.msg)
        getCategoriesList()
    } else {
        ElMessage.info('已取消删除')
    }
}

onMounted(() => {
    getCategoriesList()
})

</script>

<template>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator=">">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
        <el-button type="primary" @click="addCateDialog">添加分类</el-button>
        <el-table :data="categorieslist" style="width: 100%" row-key="cat_id" border lazy
            :tree-props="{ children: 'children' }">
            <el-table-column prop="cat_name" label="商品分类" />
            <el-table-column label="是否有效">
                <template v-slot="scope">
                    <el-icon v-if="!scope.row.cat_deleted" color="#41b883">
                        <CircleCheck />
                    </el-icon>
                    <el-icon v-else color="#cb301a">
                        <CircleClose />
                    </el-icon>
                </template>
            </el-table-column>
            <el-table-column label="排序">
                <template v-slot="scope">
                    <el-tag size="large" v-if="scope.row.cat_level === 0">一级</el-tag>
                    <el-tag size="large" type="success" v-if="scope.row.cat_level === 1">二级</el-tag>
                    <el-tag size="large" type="warning" v-if="scope.row.cat_level === 2">三级</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template v-slot="scope">
                    <el-button type="primary" icon="Edit" size="small" @click="editDialog(scope.row)">编辑</el-button>
                    <el-button type="danger" icon="Delete" size="small" @click="delCate(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination v-model:current-page="queryInfo.pagenum" v-model:page-size="queryInfo.pagesize"
            :page-sizes="[1, 2, 3, 5]" background layout="total, sizes, prev, pager, next, jumper" :total="total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>
    <!-- 添加分类对话框 -->
    <el-dialog title="添加分类" v-model="addCateDialogVisible" width="50%" @closed="addCateDialogClosed">
        <!-- 添加分类表单 -->
        <el-form :model="addCateForm" :rules="rules" ref="addCateRef" label-width="100px">
            <el-form-item label="分类名称：" prop="cat_name">
                <el-input v-model="addCateForm.cat_name"></el-input>
            </el-form-item>
            <el-form-item label="父级分类：">
                <el-cascader v-model="actionCascader" :options="secondCateList" :props="props" clearable
                    @change="changeActionCascader" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="addCateDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="addCate">
                    提交
                </el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 修改分类对话框 -->
    <el-dialog title="添加分类" v-model="editCateDialogVisible" width="50%" @closed="editCateDialogClosed">
        <!-- 修改分类表单 -->
        <el-form :model="editCateForm" :rules="rules" ref="editCateRef" label-width="100px">
            <el-form-item label="分类名称：" prop="cat_name">
                <el-input v-model="editCateForm.cat_name"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="editCateDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="editCate">
                    提交
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style scoped></style>